import React, { useState, useEffect } from "react";
import {
  Button,
  Text,
  TextInput,
  View,
  StyleSheet,
  Pressable,
  Image,
} from "react-native";
import { Picker } from "@react-native-picker/picker";
import Icon from "react-native-vector-icons/FontAwesome";
import Icon1 from "react-native-vector-icons/FontAwesome5";
import { useNavigation } from "@react-navigation/native";
import axios from "axios";
import * as ImagePicker from "expo-image-picker";
import * as FileSystem from "expo-file-system";
import AsyncStorage from "@react-native-async-storage/async-storage";
const PostScreen = ({ route }) => {
  const navigation = useNavigation();
  const { boardName = "", boardexplain = "" } = route.params || {};
  // const [selectedBoard, setSelectedBoard] = useState('');
  const [postText, setPostText] = useState("");
  const tags = [
    "#体测",
    "#二手书",
    "#电瓶车",
    "#管理学",
    "#出书",
    "#豆腐",
    "#热搜1",
  ];
  const [isOn, setIsOn] = useState(false);
  const [image, setImage] = useState(null);
  const [time, setTime] = useState("");
  const [userInfo, setUserInfo] = useState({});
  const [dy_id, setDy_id] = useState("");
  const getFormattedCurrentTime = () => {
    const now = new Date(); // 获取当前时间
    const year = now.getFullYear(); // 年
    const month = (now.getMonth() + 1).toString().padStart(2, "0"); // 月，月份是从0开始计数的
    const day = now.getDate().toString().padStart(2, "0"); // 日
    const hours = now.getHours().toString().padStart(2, "0"); // 时
    const minutes = now.getMinutes().toString().padStart(2, "0"); // 分
    const seconds = now.getSeconds().toString().padStart(2, "0"); // 秒

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  useEffect(() => {
    (async () => {
      const userinfo = await AsyncStorage.getItem("userInfo");
      if (userinfo) {
        setUserInfo(JSON.parse(userinfo));
      }
      await axios
        .get("http://47.111.227.58:3000/dynamic/getdynamic")
        .then((res) => {
          // console.log(res.data);
          console.log(res.data.results[0].id);
          // dy_id = res.data.results[0].id
          setDy_id(res.data.results[0].id);
        });
      // console.log(userinfo)
      const currentTime = getFormattedCurrentTime();
      // console.log(currentTime)
      setTime(currentTime);
      console.log(time);
      // 请求权限
      const { status } =
        await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== "granted") {
        console.log("拒绝访问图片库权限！");
      }
    })();
  }, []);
  const convertImageToBase64 = async (imageUri) => {
    try {
      const base64Data = await FileSystem.readAsStringAsync(imageUri, {
        encoding: FileSystem.EncodingType.Base64,
      });
      return base64Data;
    } catch (error) {
      console.error(error);
    }
  };

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 4],
      quality: 1,
    });

    console.log(result.assets[0]);

    // 检查图片是否是Base64格式
    if (!/^data:image\/[a-zA-Z]*;base64,/.test(result.assets[0].uri)) {
      convertImageToBase64(result.assets[0].uri)
        .then((base64Data) => {
          console.log("Image (base64): ", base64Data);
          setImage("data:image/jpg;base64," + base64Data);
        })
        .catch((err) => {
          console.error("Error converting image to base64", err);
        });
    } else {
      setImage(result.assets[0].uri);
    }
  };
  const pickVideo = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Videos,
      allowsEditing: false,
      quality: 1, // 视频选择不支持编辑，此选项可以设置视频的质量
    });
    if (!result.canceled) {
      const video = result.assets[0];
      console.log(video);
      // 视频的本地 URI 在 video.uri
    }
  };
  const toggleSwitch = () => {
    setIsOn((previousState) => !previousState);
  };
  const handlePost = async () => {
    const currentTime = getFormattedCurrentTime();
    // console.log(currentTime)
    setTime(currentTime);
    console.log(time);
    // setTime(getFormattedCurrentTime())
    axios
      .post("http://47.111.227.58:3000/dynamic/addDynamic", {
        data: {
          username: userInfo.username,
          phone: userInfo.phone,
          desc: postText,
          userImg: userInfo.imgUrl,
          uploadTime: time,
          imgUrl: image,
          board: boardName,
        },
      })
      .then((response) => {
        console.log(response.data);
        axios
          .post("http://47.111.227.58:3000/dynamic/updataIdCharacter", {
            data: {
              character: Number(userInfo.characters) + 1,
              id: userInfo.id,
            },
          })
          .then((res) => {
            console.log(res.data);
            userInfo.characters = Number(userInfo.characters) + 1;
            AsyncStorage.setItem("userInfo", JSON.stringify(userInfo));
          });
      })
      .catch((error) => {
        console.error(error);
      });
    console.log("发布的板块: ", boardName);
    console.log("发布的正文: ", postText);
    setPostText("");
    setImage(null);
    if (isOn) {
      axios
        .post("http://10.66.59.22:8501/chat/chat", {
          query: postText,
          conversation_id: "",
          history_len: -1,
          history: [
            {
              role: "user",
              content:
                "你是一个活跃在校友圈评论区的一名机器人，名叫呆呆学长，你可以根据学生发的帖子信息，回复学生的帖子。例如学生发的贴文动态是“今天天气真不错”，你需要回“哈哈哈，是的，我也觉得今天天气很棒”",
            },
            {
              role: "assistant",
              content: "好的",
            },
          ],
          stream: false,
          model_name: "chatglm3-6b",
          temperature: 0.7,
          max_tokens: 0,
          prompt_name: "default",
        })
        .then(async (res) => {
          const AIText = JSON.parse(res.data.replace("data:", "").trim()).text;
          console.log(JSON.parse(res.data.replace("data:", "").trim()).text);
          console.log(dy_id);
          await axios
            .get("http://47.111.227.58:3000/dynamic/getdynamic")
            .then(async (res) => {
              // console.log(res.data);
              // console.log(res.data.results[0].id)
              // dy_id = res.data.results[0].id
              setDy_id(res.data.results[0].id);
              await axios
                .post("http://47.111.227.58:3000/dynamic/addcomments", {
                  data: {
                    dy_id: dy_id + 1,
                    username: "呆呆学长",
                    phone: userInfo.phone,
                    userImg: "http://47.111.227.58:3000/images/daidai.png",
                    content: AIText,
                    uploadTime: time,
                  },
                })
                .then((res) => {
                  console.log(res.data);
                });
            });
        });
    }
  };

  const deleteButton = () => {
    setImage(null);
  };

  return (
    <View>
      <View style={styles.container}>
        <Text style={styles.hotIcon}>热搜</Text>
        {tags.map((tag, index) => (
          <View key={index} style={styles.tag}>
            <Text style={styles.tagText}>{tag}</Text>
          </View>
        ))}
      </View>
      <View style={styles.sectionText}>
        <Pressable onPress={() => navigation.navigate("Chooseplate")}>
          <View style={styles.sectionTextTop}>
            <Icon
              name="bars"
              style={styles.sectionTextTopIcon}
              size={20}
              color="#BABABA"
            />
            <Text style={styles.sectionTextTopTitle}>
              {boardName || "选择板块"}
            </Text>
            <Text style={styles.sectionTextTopTag}>{">"}</Text>
          </View>
          <View style={styles.sectionTextBottom}>
            <Text
              style={[
                styles.sectionTextBottomContent,
                boardexplain ? { color: "#EB4E3D", fontSize: 11 } : {},
              ]}
            >
              {boardexplain || "板块格式说明"}
            </Text>
          </View>
        </Pressable>
      </View>
      <View style={styles.content}>
        <View style={styles.contentTop}>
          <TextInput
            style={styles.input}
            multiline={true}
            placeholder="在此处输入正文..."
            placeholderTextColor="#BABABA"
            onChangeText={(text) => setPostText(text)}
            value={postText}
          />
          <View style={styles.contentTopRight}>
            <View style={styles.contentTopRightIcon}>
              <Icon
                name="map-marker"
                style={styles.contentTopRightIconItem}
                size={20}
                color="#969696"
              />
              <Icon
                name="align-left"
                style={styles.contentTopRightIconItem}
                size={20}
                color="#969696"
              />
              <Icon
                name="smile-o"
                style={styles.contentTopRightIconItem}
                size={20}
                color="#969696"
              />
              <Icon
                name="folder-o"
                style={styles.contentTopRightIconItem}
                size={20}
                color="#969696"
              />
            </View>
          </View>
        </View>
        <View style={styles.contentBottom}>
          <Pressable onPress={pickImage}>
            {!image ? (
              <View style={styles.contentBottomimage}>
                <Icon
                  name="photo"
                  style={styles.contentBottomIcon}
                  size={20}
                  color="#969696"
                />
                <Text style={styles.contentBottomText}>添加图片</Text>
              </View>
            ) : null}
            {image && (
              <>
                <Image
                  source={{ uri: image }}
                  style={{ width: 70, height: 70, marginLeft: 10 }}
                />
                <Pressable
                  onPress={deleteButton}
                  style={styles.deleteButton}
                >
                  <Icon name="window-close" size={15} color="#ff0000" />
                </Pressable>
              </>
            )}
          </Pressable>
          <Pressable onPress={pickVideo}>
            {!image ? (
              <View style={styles.contentBottomvideo}>
                <Icon
                  name="video-camera"
                  style={styles.contentBottomIcon}
                  size={20}
                  color="#969696"
                />
                <Text style={styles.contentBottomText}>添加视频</Text>
              </View>
            ) : null}
            {/* {image && (
                            <><Image source={{ uri: image }} style={{ width: 70, height: 70, marginLeft: 10 }} /><Pressable onPress={deleteButton} style={styles.deleteButton}>
                                <Icon name="window-close" size={15} color="#ff0000" />
                            </Pressable></>
                        )} */}
          </Pressable>
        </View>
      </View>
      <View style={styles.blank}></View>
      <View style={styles.AI}>
        <View style={styles.AILeft}>
          <View style={styles.AILeftTop}>
            <Icon1
              name="robot"
              style={styles.AIIcon}
              size={15}
              color="#969696"
            />
            <Text style={styles.AIText1}>AI协助</Text>
            <Text style={styles.AIText2}>限时免费</Text>
          </View>
          <View style={styles.AILeftBottom}>
            <Text style={styles.AIText3}>
              邀请基于大模型技术的 AI 助手@呆呆学长回答问题
            </Text>
          </View>
        </View>
        <View style={styles.AIRight}>
          <Pressable onPress={toggleSwitch} style={styles.AIRightbutton}>
            <Icon1
              name={isOn ? "toggle-on" : "toggle-off"}
              style={styles.AIRightbutton}
              size={30}
              color="#969696"
            />
          </Pressable>
        </View>
      </View>
      <Text style={styles.BottomText}>
        *请务必遵守 社区规范 ，如有违规会被删帖、禁言乃至封号
      </Text>
      <Pressable onPress={handlePost} style={styles.BottomButton}>
        <Text style={styles.BottomButtonText}>发布</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  deleteButton: {
    position: "absolute",
    top: -5,
    right: -5,
  },
  container: {
    flexDirection: "row",
    alignItems: "center",
    padding: 10,
    height: 30,
    marginBottom: 10,
    marginTop: 5,
    overflowY: "hidden",
    overflowX: "auto",
  },
  sectionText: {
    flexDirection: "column",
    height: 100,
    backgroundColor: "#fff",
    borderBottomWidth: 2,
    borderBottomColor: "#F4F4F4",
  },
  sectionTextTop: {
    flexDirection: "row",
    height: 50,
    backgroundColor: "#fff",
  },
  sectionTextTopIcon: {
    marginTop: 17,
    marginLeft: 10,
  },
  sectionTextTopTitle: {
    color: "#000",
    fontSize: 16,
    fontWeight: "bold",
    marginLeft: 10,
    marginTop: 15,
  },
  sectionTextTopTag: {
    color: "#BABABA",
    fontSize: 20,
    fontWeight: "bold",
    marginTop: 15,
    marginRight: 20,
    marginLeft: "auto",
  },
  sectionTextBottom: {
    height: 48,
    backgroundColor: "#fff",
  },
  sectionTextBottomContent: {
    color: "#BABABA",
    fontSize: 14,
    marginLeft: 10,
    marginTop: 10,
  },
  content: {
    height: 250,
    backgroundColor: "#fff",
  },
  contentTop: {
    height: 175,
    flexDirection: "row",
  },
  contentBottom: {
    height: 75,
    backgroundColor: "#fff",
    flexDirection: "row",
  },
  contentBottomimage: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomvideo: {
    width: 70,
    height: 70,
    backgroundColor: "#F4F4F4",
    marginLeft: 10,
  },
  contentBottomIcon: {
    position: "absolute",
    top: "25%",
    left: "34%",
  },
  contentBottomText: {
    position: "absolute",
    top: "55%",
    left: "21%",
    color: "#BABABA",
    fontSize: 10,
  },
  input: {
    height: 175,
    width: "80%",
    padding: 10,
  },
  contentTopRight: {
    height: 175,
    width: "20%",
    flexDirection: "column",
  },
  contentTopRightIcon: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F4F4F4",
    margin: 25,
    marginLeft: 30,
    marginRight: 10,
  },
  contentTopRightIconItem: {
    margin: 5,
  },
  AI: {
    height: 50,
    backgroundColor: "#fff",
    flexDirection: "row",
  },
  AILeft: {
    flexDirection: "column",
  },
  AIRight: {
    display: "flex",
  },
  AIRightbutton: {
    display: "flex",
    marginTop: 5,
    marginLeft: 28,
    marginRight: 15,
  },
  AILeftTop: {
    flexDirection: "row",
  },
  AILeftBottom: {},
  AIIcon: {
    marginTop: 5,
    marginLeft: 5,
  },
  AIText1: {
    color: "#000",
    fontSize: 14,
    fontWeight: "bold",
    marginTop: 4,
    marginLeft: 5,
  },
  AIText2: {
    backgroundColor: "#FF503B",
    color: "#fff",
    fontSize: 10,
    fontWeight: "bold",
    marginTop: 5,
    marginLeft: 5,
    padding: 2,
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
  },
  AIText3: {
    color: "#797979",
    fontSize: 11,
    marginTop: 5,
    marginLeft: 5,
  },
  BottomText: {
    color: "#BABABA",
    fontSize: 10,
    marginTop: 5,
    marginLeft: 5,
  },
  BottomButton: {
    backgroundColor: "#EB7A76",
    color: "#fff",
    padding: 10,
    marginRight: 15,
    marginLeft: 15,
    borderRadius: 20,
    marginTop: 20,
    alignItems: "center",
    justifyContent: "center",
  },
  BottomButtonText: {
    color: "#fff",
    fontWeight: "bold",
    fontSize: 14,
  },
  hotIcon: {
    width: 20,
    height: 35,
    marginRight: 10,
    backgroundColor: "red",
    color: "#fff",
    padding: 5,
    textAlign: "center",
    fontWeight: "bold",
    alignItems: "center",
    fontSize: 10,
    fontWeight: "bold",
  },
  tag: {
    backgroundColor: "#fff",
    borderRadius: 0,
    paddingHorizontal: 10,
    margin: 5,
  },
  tagText: {
    color: "#000",
  },
  blank: {
    height: 5,
    backgroundColor: "#F4F4F4",
  },
});

export default PostScreen;
